﻿using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;

namespace TerrainContent
{
    public class TerrainQuadtreeNode
    {
        public TerrainQuadtreeNode Parent;
        public TerrainQuadtreeNode[] Children;
        public Rectangle Area;
        public int MinAlt;
        public int MaxAlt;
        public int LOD;


        private bool _boundInit;
        private BoundingBox _bounds;
        private BoundingBox _Bounds
        {
            get
            {
                if (!_boundInit)
                {
                    _bounds = new BoundingBox(new Vector3(Area.X, MinAlt, Area.Y), new Vector3(Area.X + Area.Width, MaxAlt, Area.Y + Area.Height));
                    _boundInit = true;
                }
                return _bounds;
            }
        }
        public bool PickNode(ITerrainImpl terrain, BoundingSphere[] ranges, int lodLevel, BoundingFrustum frustum, Vector3 cameraPosition)
        {
            ranges[lodLevel].Center = cameraPosition;
            if (!_Bounds.Intersects(ranges[lodLevel]))
            {
                return false;
            }
            /*if (!_Bounds.Intersects(frustum))
            {
                return true;
            }*/
            if (lodLevel == 0)
            {
                terrain.PickedNodes.Add(this);
                return true;
            }
            ranges[lodLevel - 1].Center = cameraPosition;
            if (!_bounds.Intersects(ranges[lodLevel-1]))
            {
                terrain.PickedNodes.Add(this);
            }
            else
            {
                foreach (var child in Children)
                {
                    if (!child.PickNode(terrain, ranges, lodLevel - 1, frustum, cameraPosition))
                        terrain.PickedPartialNodes.Add(new KeyValuePair<Rectangle, TerrainQuadtreeNode>(child.Area, this));
                }
            }
            return true;
        }
    }
}